package com.wang.mall.controller;

import com.wang.mall.bean.SysRole;
import com.wang.mall.model.R;
import com.wang.mall.service.SysRoleMenuService;
import com.wang.mall.service.SysRoleService;
import com.wang.mall.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sys/role")
public class SysRoleController {



    @Autowired
    private SysRoleService sysRoleService;


    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 角色列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:role:list')")
    public R list(Integer page, Integer limit, String roleName) {
        PageUtils pagea = sysRoleService.queryPage(page, limit, roleName);
        return R.ok(pagea);
    }

    /**
     * 角色列表
     */
    @GetMapping("/select")
    @PreAuthorize("hasAuthority('sys:role:list')")
    public R select() {

        List<SysRole> list = sysRoleService.select();

        return R.ok(list);
    }

    /**
     * 角色信息
     */
    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/info/{roleId}")
    public R info(@PathVariable("roleId") Long roleId) {
        SysRole role = sysRoleService.getById(roleId);

        //查询角色对应的菜单
        List<Long> menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
        role.setMenuIdList(menuIdList);

        return R.ok(role);
    }

    /**
     * 保存角色
     */
    @PreAuthorize("hasAuthority('sys:role:save')")
    @PostMapping("/save")
    public R save(@RequestBody SysRole role) {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());

        role.setCreateUserId(userId);
        sysRoleService.saveRole(role);

        return R.ok();
    }

    /**
     * 修改角色
     */
    @PreAuthorize("hasAuthority('sys:role:update')")
    @PostMapping("/update")
    public R update(@RequestBody SysRole role) {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());

        role.setCreateUserId(userId);
        sysRoleService.update(role);

        return R.ok();
    }

    /**
     * 删除角色
     */
    @PreAuthorize("hasAuthority('sys:role:delete')")
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] roleIds) {
        sysRoleService.deleteBatch(roleIds);

        return R.ok();
    }
}
